package com.newgoldcurrency.activities;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.newgoldcurrency.App;
import com.newgoldcurrency.R;
import com.newgoldcurrency.databinding.ActivityDeleteAccountBinding;
import com.newgoldcurrency.utils.CancelCall;
import com.newgoldcurrency.utils.Tools;
import com.newgoldcurrency.utils.network.Network;
import com.newgoldcurrency.view.VerificationCodeView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class DeleteAccountActivity extends AppCompatActivity {
    private final List<Call> calls=new ArrayList<>();
    int time=60;
    Handler handler=new Handler();
    Runnable runnable=new Runnable() {
        @SuppressLint("SetTextI18n")
        @Override
        public void run() {
            if (time>0){
                time--;
                handler.postDelayed(this,1000);
                if (binding!=null)binding.deleteAccountSendButton.setText(time+"s");
            }else {
                time=60;
                if (binding!=null)binding.deleteAccountSendButton.setText("Send");
            }
        }
    };
    private ActivityDeleteAccountBinding binding;
    private String verifycode="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         binding = ActivityDeleteAccountBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.deleteAccountUsername.setText(getString(R.string.account_username,App.userBean.invitation_code));
        binding.deleteAccountMail.setText(App.userBean.mail);
        binding.deleteAccountBack.setOnClickListener(view -> finish());
        binding.deleteAccountSendButton.setOnClickListener(view -> {
            if (time==60){
                HashMap<String, String> map=new HashMap<>();
                map.put("mail",binding.deleteAccountMail.getText().toString());
                map.put("type","cancel");
                Network.post(map, "user/getVerificationCode", call -> {
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(@NonNull Call call, @NonNull IOException e) {e.printStackTrace();}
                        @Override
                        public void onResponse(@NonNull Call call, @NonNull Response response) {
                            runOnUiThread(() -> {
                                try {
                                    String str = Objects.requireNonNull(response.body()).string();
                                    if (Tools.isJson(str)) {
                                        JsonObject jo = JsonParser.parseString(str).getAsJsonObject();
                                        if (jo.get("message").getAsString().equals("Sent successfully")) {
                                            startDelay();
                                        }
                                        Tools.toast(jo.get("message").getAsString());
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            });
                        }
                    });
                    calls.add(call);
                });
            }else{
                Tools.toast(getString(R.string.please_wait_count_down));
            }
        });
        binding.deleteAccountVc.setOnCodeFinishListener(new VerificationCodeView.OnCodeFinishListener() {
            @Override
            public void onTextChange(View view, String content) {

            }
            @Override
            public void onComplete(View view, String content) {
                 verifycode=content;
            }
        });
        binding.deleteAccountDeleteButton.setOnClickListener(view -> Tools.dialog_delete_account(this, view1 -> {
            if (!verifycode.equals("")){
                HashMap<String, String> map=new HashMap<>();
                map.put("token",App.sp.getString("token",""));
                map.put("code",verifycode);
                map.put("mail",App.userBean.mail);
                Network.post(map, "user/deleteAccount", (CancelCall) call -> {
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(@NonNull Call call, @NonNull IOException e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(@NonNull Call call, @NonNull Response response) {
                            runOnUiThread(() -> {
                                try {
                                    String result=JsonParser.parseString(response.body().string()).getAsJsonObject().get("message").getAsString();
                                    Tools.toast(result);
                                    if (result.equals("Delete Account Success")){
                                        setResult(4);
                                        finish();
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            });
                        }
                    });
                    calls.add(call);
                });
            }else {
                Tools.toast(getString(R.string.verify_code_not_empty));
            }
        }));
    }

    private void startDelay() {
        handler.postDelayed(runnable,0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable);
        for (Call c :calls) c.cancel();
    }
}